package Part1_java.util.Collection.Set.TreeSet;

import org.junit.Test;

import java.util.Comparator;
import java.util.TreeSet;

/**
 * ClassName: Test
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.04.14 9:50
 */
public class Test1 {
    @Test
    public void test1(){
        TreeSet<Object> set = new TreeSet<>();

        set.add("cc");
        set.add("ee");
        set.add("dd");
        set.add("bb");
        set.add("aa");
        //set.add(123); 报异常:ClassCastException
        //TreeSet 添加的元素要是同一类型
        System.out.println(set);
    }

    @Test
    public void test2(){
        //自然排序：Comparable接口实现
        TreeSet<Object> set = new TreeSet<>();

        set.add(new User("Tom",12));
        set.add(new User("Tom",12));
        set.add(new User("T",12));  //按照User中重写的compareTo方法的标准，age属性一样即为一样的
        set.add(new User("Boss",92));

        System.out.println(set);
        //ClassCastException: User cannot be cast to Comparable
        //因为User类没有实现Comparable接口
    }

    @Test
    public void test3(){
        //定制排序：Comparator接口实现

        Comparator comparator = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof User && o2 instanceof User){
                    User u1 = (User) o1;
                    User u2 = (User) o2;

                    int vulue = u1.getName().compareTo(u2.getName());//先比较name
                    if(vulue!=0)
                        return vulue;
                    return u1.getAge() - u2.getAge();//如果name一样，则比较age
                }
                throw new RuntimeException("类型不匹配");
            }
        };

        TreeSet<Object> set = new TreeSet<>(comparator);

        set.add(new User("Tom",12));
        set.add(new User("Tom",12));
        set.add(new User("Tom",13));
        set.add(new User("T",12));
        set.add(new User("Boss",92));

        System.out.println(set.size());
        System.out.println(set);
    }
}
